<template>
  <div class="ledger-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col :span="8">
        <el-card class="statistics-card" shadow="hover">
          <div class="statistics-header">
            <span class="label">本月总收入</span>
            <el-icon class="icon"><Money /></el-icon>
          </div>
          <div class="statistics-value">
            ¥{{ monthlyIncome }}
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="statistics-card" shadow="hover">
          <div class="statistics-header">
            <span class="label">本月订单数</span>
            <el-icon class="icon"><Document /></el-icon>
          </div>
          <div class="statistics-value">
            {{ monthlyOrders }}
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="statistics-card" shadow="hover">
          <div class="statistics-header">
            <span class="label">平均客单价</span>
            <el-icon class="icon"><PriceTag /></el-icon>
          </div>
          <div class="statistics-value">
            ¥{{ averagePrice }}
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <span>本月线路销售分析</span>
              <el-radio-group v-model="routeChartType" size="small">
                <el-radio-button label="amount">销售额</el-radio-button>
                <el-radio-button label="count">订单量</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="routeChartRef" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <span>上月分公司业绩占比</span>
            </div>
          </template>
          <div ref="branchChartRef" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 账单明细 -->
    <el-card class="table-card" shadow="hover" :body-style="{ padding: '0px' }" v-loading="loading">
      <template #header>
        <div class="table-header">
          <span>账单明细</span>
          <div class="table-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
              :disabled-date="disabledDate"
              :default-time="[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 1, 1, 23, 59, 59)
              ]"
              unlink-panels
              size="small"
              style="width: 260px"
            />
            <el-button 
              type="primary" 
              :icon="Download" 
              size="small"
              @click="exportExcel"
            >导出Excel</el-button>
          </div>
        </div>
      </template>
      <el-table 
        :data="paginatedLedgerList"
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa' }"
        border>
        <el-table-column prop="travelStartTime" label="订单时间" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.travelStartTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="顾客姓名" width="120" align="center" />
        <el-table-column prop="routeName" label="线路名称" min-width="180" align="center" />
        <el-table-column prop="totalIncome" label="金额" width="120" align="center">
          <template #default="scope">
            ¥{{ scope.row.totalIncome }}
          </template>
        </el-table-column>
        <el-table-column prop="guideName" label="导游姓名" width="120" align="center" />
        <el-table-column prop="branchName" label="所属分公司" width="150" align="center" />
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed, nextTick, onUnmounted } from 'vue'
import { Money, Document, PriceTag, Download, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import type { EChartOption } from 'echarts'
import { ledgerApi } from '@/api'
import * as XLSX from 'xlsx'

// 添加类型定义
interface LedgerItem {
  travelStartTime: string
  customerName: string
  routeName: string
  totalIncome: number
  guideName: string
  branchName: string
}

interface RouteStatistics {
  routeName: string
  totalIncome: number
  orderCount: number
}

interface BranchStatistics {
  branchName: string
  totalSales: number
  color: string
}

// 数据定义
const monthlyIncome = ref<number>(0)
const monthlyOrders = ref<number>(0)
const averagePrice = ref<number>(0)
const monthlyGrowth = ref(5.2)
const ordersGrowth = ref(-2.1)
const priceGrowth = ref(7.5)

// 图表相关
const routeChartRef = ref<HTMLElement>()
const branchChartRef = ref<HTMLElement>()
const routeChartType = ref<'amount' | 'count'>('amount')
const branchTimeRange = ref<string>('month')
const dateRange = ref<[Date, Date] | null>(null)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const ledgerList = ref<LedgerItem[]>([])

let routeChart: echarts.ECharts | null = null
let branchChart: echarts.ECharts | null = null

// 添加 loading ref
const loading = ref(false)

// 分页处理函数
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1  // 重置到第一页
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 添加分页样式
const paginationStyle = {
  marginTop: '20px',
  textAlign: 'right' as const // 添加类型断言
}

// 计算分页数据
const paginatedLedgerList = computed(() => {
  // 首先根据时间范围筛选数据
  let filteredData = ledgerList.value
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = new Date(dateRange.value[0]).getTime()
    const endDate = new Date(dateRange.value[1]).getTime()
    filteredData = filteredData.filter((item: { travelStartTime: string | number | Date }) => {
      const itemDate = new Date(item.travelStartTime).getTime()
      return itemDate >= startDate && itemDate <= endDate
    })
  }

  // 按时间降序排序
  filteredData.sort((a: { travelStartTime: string | number | Date }, b: { travelStartTime: string | number | Date }) =>
    new Date(b.travelStartTime).getTime() - new Date(a.travelStartTime).getTime()
  )

  // 更新总数（这很重要，确保分页器显示正确的总数）
  total.value = filteredData.length
  
  // 计算当前页的数据
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.slice(start, end)
})

// 添加日期格式化函数
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}年${month}月${day}日`
}

// 获取账单统计数据
const fetchStatistics = async () => {
  try {
    // 获取路线统计数据
    const routeData = await ledgerApi.getRouteStatistics()
    if (routeData && routeData.length > 0) {
      // 计算总收入
      monthlyIncome.value = routeData.reduce((sum: number, item: any) => 
        sum + (item.totalIncome || 0), 0).toFixed(2)
      
      // 计算总订单数
      monthlyOrders.value = routeData.reduce((sum: number, item: any) => 
        sum + (item.orderCount || 0), 0)
        
      // 计算平均客单价
      averagePrice.value = monthlyOrders.value > 0 
        ? (monthlyIncome.value / monthlyOrders.value).toFixed(2)
        : '0.00'
        
      initRouteChart(routeData)
    }

    // 获取分公司统计数据
    const branchData = await ledgerApi.getBranchStatistics()
    if (branchData && branchData.length > 0) {
      initBranchChart(branchData)
    }
  } catch (error) {
    ElMessage.error('获取统计数据失败')
    console.error('Error fetching statistics:', error)
  }
}

// 修改取账单明细的函数
const fetchLedgerList = async () => {
  try {
    const data = await ledgerApi.getAllLedgers()
    // 处理数据格式并按时间降序排序
    ledgerList.value = data.map((item: any) => ({
      travelStartTime: item.time,
      customerName: item.name,
      routeName: item.routeName,
      totalIncome: item.money,
      guideName: item.emName,
      branchName: item.branchName
    })).sort((a: { travelStartTime: string | number | Date }, b: { travelStartTime: string | number | Date }) =>
      new Date(b.travelStartTime).getTime() - new Date(a.travelStartTime).getTime()
    )
    total.value = ledgerList.value.length
  } catch (error) {
    ElMessage.error('获取账单数据失败')
  }
}

// 初始化线路统计图表
const initRouteChart = (data: any) => {
  if (!routeChart) return
  
  const option: EChartOption = {
    title: {
      text: routeChartType.value === 'amount' ? '本月线路销售额统计' : '本月线路订单量统计',
      left: 'center',
      top: 20,
      textStyle: {
        color: '#303133',
        fontSize: 16,
        fontWeight: 'normal' as const
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map((item: any) => item.routeName),
      axisLabel: {
        interval: 0,
        rotate: 30,
        formatter: (value: string) => {
          // 每隔 10 个字符添加换行符
          const length = 10;
          const rows = Math.ceil(value.length / length);
          const newValue = [];
          for (let i = 0; i < rows; i++) {
            newValue.push(value.slice(i * length, (i + 1) * length));
          }
          return newValue.join('\n');
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value: number) => 
          routeChartType.value === 'amount' ? '¥' + value : value
      }
    },
    series: [
      {
        name: routeChartType.value === 'amount' ? '销售额' : '订单量',
        type: 'bar',
        barWidth: '40%',
        data: data.map((item: any) => ({
          value: routeChartType.value === 'amount' ? item.totalIncome : item.orderCount,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          }
        })),
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#188df0' },
              { offset: 0.7, color: '#188df0' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        }
      }
    ]
  }
  routeChart.setOption(option)
}

// 始化分公司统计图表
const initBranchChart = (data: any) => {
  if (!branchChart) return
  
  const option: EChartOption = {
    title: {
      text: '上月分公司业绩占比',
      left: 'center',
      top: 20,
      textStyle: {
        color: '#303133',
        fontSize: 16,
        fontWeight: 'normal' as const
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}元 ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: '5%',
      left: 'center'
    },
    series: [
      {
        type: 'pie',
        radius: ['30%', '60%'],
        center: ['50%', '45%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}\n{c}元\n{d}%'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold' as const
          }
        },
        data: data.map((item: any) => ({
          name: item.branchName,
          value: item.totalSales || 0,
          itemStyle: {
            color: item.color
          }
        }))
      }
    ]
  }
  branchChart.setOption(option)
}

// 监听图表类型变化
watch(routeChartType, () => {
  fetchStatistics()
})

// 监听时间范围变化
watch(dateRange, () => {
  // 重置分页到第一页
  currentPage.value = 1
})

// 添加日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    }
  }
]

// 修改日期限制函数
const disabledDate = (time: Date) => {
  // 只限制��能选择未来的日期
  return time.getTime() > Date.now()
}

// 添加导出Excel功能
const exportExcel = () => {
  try {
    ElMessage.info('正在生成Excel，请稍候...')
    
    // 使用筛选后的数据
    const exportData = paginatedLedgerList.value.map((item: { travelStartTime: string; customerName: any; routeName: any; totalIncome: any; guideName: any; branchName: any }) => ({
      '订单时间': formatDate(item.travelStartTime),
      '顾客姓名': item.customerName,
      '线路名称': item.routeName,
      '金额': item.totalIncome,
      '导游姓名': item.guideName,
      '所属分公司': item.branchName
    }))

    // 创建工作簿
    const wb = XLSX.utils.book_new()
    
    // 创建工作表
    const ws = XLSX.utils.json_to_sheet(exportData)
    
    // 设置列宽
    const colWidths = [
      { wch: 15 }, // 订单时间
      { wch: 10 }, // 顾客姓名
      { wch: 20 }, // 线路名称
      { wch: 10 }, // 金额
      { wch: 10 }, // 导游姓名
      { wch: 15 }  // 所属分公司
    ]
    ws['!cols'] = colWidths

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '账单明细')
    
    // 生成Excel文件
    XLSX.writeFile(wb, `账单明细_${formatDate(new Date().toString())}.xlsx`)
    
    ElMessage.success('Excel导出成功')
  } catch (error) {
    console.error('Error exporting Excel:', error)
    ElMessage.error('Excel导出失败')
  }
}

onMounted(() => {
  // 先初始化图表实例
  nextTick(() => {
    routeChart = echarts.init(routeChartRef.value)
    branchChart = echarts.init(branchChartRef.value)
    
    // 然后获取数据
    fetchStatistics()
    fetchLedgerList()
  })
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    routeChart?.resize()
    branchChart?.resize()
  })
})

// 添加��件卸载时的清理
onUnmounted(() => {
  // 销毁表实例
  routeChart?.dispose()
  branchChart?.dispose()
  
  // 移除事件监听
  window.removeEventListener('resize', () => {
    routeChart?.resize()
    branchChart?.resize()
  })
})
</script>

<style scoped>
.ledger-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
  padding-bottom: 240px; /* 增加更多底部留白 */
}

.statistics-row {
  margin-bottom: 20px;
}

.statistics-card {
  height: 180px;
  padding: 20px;
  transition: all 0.3s;
}

.statistics-card:hover {
  transform: translateY(-4px);
}

.statistics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.statistics-header .label {
  font-size: 16px;
  color: #606266;
}

.statistics-header .icon {
  font-size: 24px;
  color: #409EFF;
}

.statistics-value {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin: 20px 0;
  font-family: "DIN Alternate", "Arial", sans-serif;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 500px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.chart {
  height: 440px;
}

.table-card {
  margin-bottom: 20px;
  position: relative; /* 确保分页器相对于卡片定位 */
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-actions {
  display: flex;
  gap: 16px;
}

.pagination {
  margin-top: 20px;
  padding: 10px 20px;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
  position: sticky;
  bottom: 80px; /* 相应调整分页器距离底部的距离 */
  z-index: 10;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05); /* 添加轻微阴影效果 */
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  margin: 0;
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  font-weight: 600;
}

:deep(.el-pagination) {
  padding: 0;
  margin: 0;
}

:deep(.el-pagination .el-select .el-input) {
  width: 100px;
}

:deep(.el-pagination .el-pagination__total) {
  margin-right: 16px;
}

:deep(.el-pagination .el-pagination__sizes) {
  margin-right: 16px;
}

/* 添加导出时的loading状态样式 */
.exporting {
  pointer-events: none;
  opacity: 0.7;
}
</style> 